const http = require('http');
const https = require('https');
const httpProxy = require('http-proxy');
const forge = require('node-forge');
const fs = require('fs');

const PROXY_PORT = 8080;
const DATA_FILE = 'requests.json';

let requestsData = [];

try {
    requestsData = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
} catch (err) {
    console.error('Failed to read requests data:', err);
}

function saveRequestsData() {
    fs.writeFileSync(DATA_FILE, JSON.stringify(requestsData, null, 2));
}

// 生成自签名证书
const pki = forge.pki;
const keys = pki.rsa.generateKeyPair(2048);
const cert = pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
const attrs = [{ name: 'commonName', value: 'localhost' }];
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.sign(keys.privateKey);

const certPem = pki.certificateToPem(cert);
const keyPem = pki.privateKeyToPem(keys.privateKey);

// 创建代理服务器
const proxy = httpProxy.createProxyServer({});

proxy.on('proxyReq', (proxyReq, req, res) => {
    const requestData = {
        timestamp: new Date().toISOString(),
        method: req.method,
        url: req.url,
        headers: req.headers,
    };

    requestsData.push(requestData);
    saveRequestsData();
});

proxy.on('proxyRes', (proxyRes, req, res) => {
    const responseData = {
        timestamp: new Date().toISOString(),
        statusCode: proxyRes.statusCode,
        headers: proxyRes.headers,
    };

    requestsData.push(responseData);
    saveRequestsData();
});

proxy.on('error', (err, req, res) => {
    console.error('Proxy error:', err);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Proxy error occurred');
});

const httpServer = http.createServer((req, res) => {
    console.log('Proxying HTTP request:', req.url);
    proxy.web(req, res, { target: `http://${req.headers.host}${req.url}` });
});

const httpsServer = https.createServer({ key: keyPem, cert: certPem }, (req, res) => {
    console.log('Proxying HTTPS request:', req.url);
    proxy.web(req, res, { target: `https://${req.headers.host}${req.url}` });
});

httpServer.listen(PROXY_PORT, () => {
    console.log(`HTTP Proxy server listening on port ${PROXY_PORT}`);
});

httpsServer.listen(PROXY_PORT + 1, () => {
    console.log(`HTTPS Proxy server listening on port ${PROXY_PORT + 1}`);
});